package wjh.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import wjh.mapper.wyDoctorMapper;

import wjh.pojo.Doctor;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class wyDoctorServiceImpl implements wyDoctorService {
    @Autowired
    private wyDoctorMapper doctorMapper;
    @Override
    public List<Doctor>like(String likename) {
        List<Doctor> like = doctorMapper.like(likename);
        return like;
    }

    @Override
    public void addDoctor(Doctor doctor, MultipartFile file, HttpServletRequest request) {
                String photo="default.jpg";
        if(file.getSize()>0){
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String prefix= UUID.randomUUID().toString().replaceAll("-","");
            photo=prefix+suffix;
            String realPath = request.getServletContext().getRealPath("/static/img/");
            //执行上传
            try {
                file.transferTo(new File(realPath,photo));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        doctor.setPhoto(photo);
doctorMapper.addDoctor(doctor);
    }

    @Override
    public void deleteDoctorByid(String ids) {
        String[] idArray = ids.split("-");
        for (String id : idArray) {
            if (!id.isEmpty()) {
                doctorMapper.deleteDoctorByid(String.valueOf(Integer.parseInt(id)));
            }
        }
    }




    @Override
    public List<Doctor> findAll() {
        return doctorMapper.findAll();
    }

    @Override
    public Doctor findDoctorById(int id) {
       return doctorMapper.findDoctorById(id);

    }

    @Override
    public void updateDoctor(Doctor doctor, MultipartFile file, HttpServletRequest request, String phname) {
        String photo=phname;
        if(file.getSize()>0){
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String prefix= UUID.randomUUID().toString().replaceAll("-","");
            photo=prefix+suffix;
            String realPath = request.getServletContext().getRealPath("/static/img/");
            //执行上传
            try {
                file.transferTo(new File(realPath,photo));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        doctor.setPhoto(photo);
        doctorMapper.updateDoctor(doctor);
    }

}
